﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EdgeDetectNormalsAndDepth : PostEffectsBase
{
    // 边缘检测Shader
    public Shader edgeDetectShader;
    // 边缘检测材质
    private Material edgeDetectMaterial = null;
    public Material material
    {
        get
        {
            edgeDetectMaterial = CheckShaderAndCreateMaterial(edgeDetectShader, edgeDetectMaterial);
            return edgeDetectMaterial;
        }
    }

    [Range(0.0f, 1.0f)]
    public float edgeOnly = 0.0f;
    // 边缘颜色
    public Color edgeColor = Color.black;
    // 背景颜色
    public Color backgroundColor = Color.white;
    // 控制深度法线纹理的采样距离，值越大，描边越宽
    public float sampleDistance = 1.0f;
    // 影响当邻域的深度值相差多少时，认定为存在边界
    public float sensitivityDepth = 1.0f;
    // 影响当邻域的法线值相差多少时，认定为存在边界
    public float sensitivityNormals = 1.0f;

    void OnEnable()
    {
        // 开启深度+法线纹理
        GetComponent<Camera>().depthTextureMode |= DepthTextureMode.DepthNormals;
    }

    // 添加ImageEffectOpaque属性，让OnRenderImage方法在不透明的Pass执行完后立刻被调用
    // （在透明Pass前，从而只对不透明物体进行描边）
    [ImageEffectOpaque]
    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (material == null)
        {
            Graphics.Blit(src, dest);
            return;
        }

        // 传递参数到Shader
        material.SetFloat("_EdgeOnly", edgeOnly);
        material.SetColor("_EdgeColor", edgeColor);
        material.SetColor("_BackgroundColor", backgroundColor);
        material.SetFloat("_SampleDistance", sampleDistance);
        material.SetVector("_Sensitivity", new Vector4(sensitivityNormals, sensitivityDepth, 0.0f, 0.0f));

        Graphics.Blit(src, dest, material);
    }
}